{% extends 'base_pages/base.html' %}

{% block title %}
    {{_("Dev Env Images")}}
{% endblock %}

{% block header %}
    <h1>{{_("Dev Env Images")}}</h1>
{% endblock %}

{% block content %}
<div style="display: flex; gap: 10px;">
    <button id="addNew">{{_("Add New")}}</button>
    <button id="exportTable">{{_("Export CSV")}}</button>
    <button id="importTable">{{_("Import CSV")}}</button>
</div>
<table id="devEnvTable">
    <thead>
        <tr>
            <th>ID</th>
            <th>{{_("Name")}}</th>
            <th>{{_("Image URL")}}</th>
            <th>{{_("Editor Type")}}</th>
            <th>{{_("Description")}}</th>
            <th>{{_("Git Repositories To Run")}}<br>(Split by ;)</th>
            <th>{{_("Actions")}}</th>
        </tr>
    </thead>
    <tbody>
        <!-- Rows will be dynamically inserted here -->
    </tbody>
</table>

<script>
    $(document).ready(function () {
        loadDevEnvImages();

        $('#addNew').click(function () {
            addNewDevEnvImage();
        });

        $('#exportTable').click(function () {
            ajaxRequest({
                url: '/dev_env_imgs/export_table',
                type: 'GET',
                success: function (data) {
                    const blob = new Blob([data], { type: 'text/csv' });
                    const url = window.URL.createObjectURL(blob);
                    const a = document.createElement('a');
                    a.href = url;
                    a.download = 'dev_env_imgs.csv';
                    document.body.appendChild(a);
                    a.click();
                    document.body.removeChild(a);
                    window.URL.revokeObjectURL(url);
                },
                error: function (e) {
                    alert('Export failed: ' + e.responseJSON.error);
                }
            });
        });

        $('#importTable').click(function () {
            const input = $('<input type="file" accept=".csv">');
            input.on('change', function (e) {
                const file = e.target.files[0];
                if (file) {
                    const formData = new FormData();
                    formData.append('file', file);
                    ajaxRequest({
                        url: '/dev_env_imgs/import_table',
                        type: 'POST',
                        data: formData,
                        processData: false,
                        contentType: false,
                        success: function () {
                            showToast('Data imported successfully');
                            loadDevEnvImages();
                        },
                        error: function (e) {
                            alert('Import failed: ' + e.responseJSON.error);
                        }
                    });
                }
            });
            input.click();
        });

        function loadDevEnvImages() {
            ajaxGet('/dev_env_imgs/dev_env_imgs', function (data) {
                $('#devEnvTable tbody').empty();
                data.forEach(function (env) {
                    $('#devEnvTable tbody').append(`
                        <tr id="sky-table-row-${env.id}">
                            <td>${env.id}</td>
                            <td class="editable" data-field="name">${env.name}</td>
                            <td class="editable" data-field="img_tag">${env.img_tag}</td>
                            <td class="editable" data-field="editor_type">${env.editor_type}</td>
                            <td class="editable" data-field="description">${env.description}</td>
                            <td class="editable" data-field="git_repositories">${env.git_repositories}</td>
                            <td>
                                <button class="delete" data-id="${env.id}">{{_("Delete")}}</button>
                            </td>
                        </tr>
                    `);
                });
                $('.editable').dblclick(function () {
                    editCell(this);
                });
                $('.delete').click(function () {
                    deleteDevEnvImage($(this).data('id'));
                });
            });
        }

        function editCell(cell) {
            // Check if the cell already contains an input element
            if ($(cell).find('input').length > 0 || $(cell).find('textarea').length > 0 || $(cell).find('select').length > 0) {
                return;
            }

            const originalValue = $(cell).text();
            let input;
            if ($(cell).data('field') === 'name') {
                input = $('<input type="text" value="' + originalValue + '">');
            } else if ($(cell).data('field') === 'editor_type') {
                input = $('<select>');
                const options = ['Code-Server', 'Jupyter Lab', 'SSH', 'Generic App'];
                options.forEach(function (option) {
                    const optionElement = $('<option>').val(option).text(option);
                    if (option === originalValue) {
                        optionElement.attr('selected', 'selected');
                    }
                    input.append(optionElement);
                });
            } else {
                input = $('<textarea rows="5">' + originalValue + '</textarea>');
            }
            $(cell).html(input);
            input.focus();
            input.blur(function () {
                const newValue = input.val();
                if (newValue !== originalValue) {
                    updateDevEnvImage($(cell).closest('tr').find('td:first').text(), $(cell).data('field'), newValue);
                }
                $(cell).text(newValue);
            });
        }

        function updateDevEnvImage(id, field, value) {
            const data = {};
            data[field] = value;
            ajaxRequest({
                url: `/dev_env_imgs/${id}`,
                type: 'PUT',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function () {
                    showToast('Data saved');
                },
                error: function (e) {
                    alert(`Update failed ${e.error}`);
                }
            });
        }

        function deleteDevEnvImage(id) {
            if (confirm('Are you sure you want to delete this item?')) { // Added confirmation dialog
                ajaxRequest({
                    url: `/dev_env_imgs/${id}`,
                    type: 'DELETE',
                    success: function () {
                        showToast('Item deleted');
                        loadDevEnvImages();
                    },
                    error: function (e) {
                        alert('Delete failed');
                    }
                });
            }
        }

        function addNewDevEnvImage() {
            const data = {
                name: `[Untitled Env#${new Date().getUTCMilliseconds()}]`,
                img_tag: '[Unknown]',
                description: '...',
                git_repositories: '...',
                editor_type: "SSH/Code-Server/Jupyter/Generic App"
            };
            ajaxRequest({
                url: '/dev_env_imgs/create',
                type: 'POST',
                contentType: 'application/json',
                data: JSON.stringify(data),
                success: function (response) {
                    const newRow = `
                        <tr>
                            <td>${response.id}</td>
                            <td class="editable" data-field="name">${data.name}</td>
                            <td class="editable" data-field="img_tag">${data.img_tag}</td>
                            <td class="editable" data-field="editor_type">${data.editor_type}</td>
                            <td class="editable" data-field="description">${data.description}</td>
                            <td class="editable" data-field="git_repositories">${data.git_repositories}</td>
                            <td>
                                <button class="delete" data-id="${response.id}">Delete</button>
                            </td>
                        </tr>
                    `;
                    $('#devEnvTable tbody').append(newRow);
                    $('.editable').dblclick(function () {
                        editCell(this);
                    });
                    $('.delete').click(function () {
                        deleteDevEnvImage($(this).data('id'));
                    });
                    alert('Added successfully');
                },
                error: function (e) {
                    //<!-- console.log(e) -->
                    alert(`Add failed: ${e.responseJSON.error}`);
                }
            });
        }

        function saveNewDevEnvImage(row) {
        }

        function showToast(message) {
            const toast = document.createElement('div');
            toast.className = 'toast';
            toast.textContent = message;
            document.body.appendChild(toast);
            setTimeout(() => {
                toast.remove();
            }, 3000); // 3 seconds
        }
    });
</script>
{% endblock %}
